let app = getApp();
let API_URL = app.globalData.API_URL;
import { getDelivery, getDeliveryDetail } from "../../../request/api.js";
import dayjs from "../../../common/js/dayjs.js";

let iconUrl = 'https://atush.vip/static/icons/';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        lang: null,
        iconUrl: iconUrl,
        topTapCurrentIndex: 0,
        currentIndex: 0,
        showAuthDialog: false,
        showUnfilledDialog: false,
        showSuccessPromptDialog: false,
        showFailPromptDialog: false,
        review: [],
        review1: [],
        editId: 0,
        destroyId: null,
        userId: 0,
        showUp_loading: false,
        locationInfo: '',
        bangActive: 0,

        // 填空
        // infoObj :{},

        orderCon: []
    },

    // my function

    // 等待上传
    waitForUpload() {
        let that = this
        setTimeout(function () {
            that.setData({ showUp_loading: false })
        }, 5000);
    },

    // 发送
    sendBTN() {
        let sender;
        let from;
        let sender_phone;
        let sender_remark;
        let receiver;
        let shipping_address;
        let shipping_phone;
        let type;
        if(this.data.orderCon.length > 0 && this.data.orderCon[0] && this.data.orderCon[0].idx == 0) {
            sender = this.data.orderCon[0].sender
            from = this.data.orderCon[0].from
            sender_phone = this.data.orderCon[0].sender_phone
            sender_remark = this.data.orderCon[0].sender_remark
        } else if (this.data.orderCon.length > 0 && this.data.orderCon[1] && this.data.orderCon[1].idx == 0) {
            sender = this.data.orderCon[1].sender
            from = this.data.orderCon[1].from
            sender_phone = this.data.orderCon[1].sender_phone
            sender_remark = this.data.orderCon[1].sender_remark
        }
        
        if (this.data.orderCon.length > 0 && this.data.orderCon[1] && this.data.orderCon[1].idx == 1) {
            receiver = this.data.orderCon[1].receiver
            shipping_address = this.data.orderCon[1].shipping_address
            shipping_phone = this.data.orderCon[1].shipping_phone
        } else if (this.data.orderCon.length > 0 && this.data.orderCon[0].idx == 1) {
            receiver = this.data.orderCon[0].receiver
            shipping_address = this.data.orderCon[0].shipping_address
            shipping_phone = this.data.orderCon[0].shipping_phone
        }

        let phoneNum_2;
        let receiver_2;
        let remark_2;
        let shipping_address_2;
        let receiver_3;
        let sender_phone_3;
        let shipping_address_3;
        if(this.data.orderCon.length > 0 && this.data.orderCon[0].idx == 2) {
            phoneNum_2 = this.data.orderCon[0].phoneNum_2
            receiver_2 = this.data.orderCon[0].receiver_2
            remark_2 = this.data.orderCon[0].remark_2
            shipping_address_2 = this.data.orderCon[0].shipping_address_2
        } else if (this.data.orderCon.length > 0 && this.data.orderCon[1] && this.data.orderCon[1].idx == 2) {
            sender = this.data.orderCon[1].sender
            from = this.data.orderCon[1].from
            sender_phone = this.data.orderCon[1].sender_phone
            sender_remark = this.data.orderCon[1].sender_remark
        }
        
        if (this.data.orderCon.length > 0 && this.data.orderCon[1] && this.data.orderCon[1].idx == 3) {
            receiver_3 = this.data.orderCon[1].receiver_3
            sender_phone_3 = this.data.orderCon[1].sender_phone_3
            shipping_address_3 = this.data.orderCon[1].shipping_address_3
        } else if (this.data.orderCon.length > 0 && this.data.orderCon[1] && this.data.orderCon[1].idx == 3) {
            receiver_3 = this.data.orderCon[1].receiver_3
            sender_phone_3 = this.data.orderCon[1].sender_phone_3
            shipping_address_3 = this.data.orderCon[1].shipping_address_3
        }
        
        let data_1;
        if (this.data.orderCon.length == 2) {
            if (this.data.orderCon[1].idx == 0 || this.data.orderCon[0].idx == 0  || this.data.orderCon[0].idx == 1 || this.data.orderCon[1].idx == 1) {
                data_1 = {sender, from, sender_phone, sender_remark, receiver, shipping_address, shipping_phone, type: 1}
            } else if (this.data.orderCon[1].idx == 2 || this.data.orderCon[0].idx == 2  || this.data.orderCon[0].idx == 3 || this.data.orderCon[1].idx == 3) {
                data_1 = {phoneNum_2, receiver_2, remark_2, shipping_address_2, receiver_3, sender_phone_3, shipping_address_3, type: 2}
            }
        }
        if ( this.data.orderCon.length < 2 ) {
            return this.setData({ showUnfilledDialog: true })
        }
        
        // 编辑后的提交
        let data_3 = { ...this.data.orderCon[0], ...this.data.orderCon[1] }
        delete data_3.releaseTime
        delete data_3.images
        delete data_3.idx
        data_3.id = this.data.editId
        if(this.data.orderCon[0].idx == 2 || this.data.orderCon[1].idx == 2 || this.data.orderCon[0].idx == 3 || this.data.orderCon[1].idx == 3) {
            data_3.type = 2
        } else if (this.data.orderCon[0].idx == 0 || this.data.orderCon[1].idx == 0 || this.data.orderCon[0].idx == 1 || this.data.orderCon[1].idx == 1) {
            data_3.type = 1
        }
        if(this.data.editId > 0) {
            let that=this;
            that.setData({ showUp_loading: true })
            that.waitForUpload()
            return wx.request({
                url: `${API_URL}/delivery`,
                data: data_3,
                header: app.header(),
                method: 'post',
                success: function (res) {
                    if(res.statusCode == 200) {
                        setTimeout(function () {
                            that.setData({ showSuccessPromptDialog: true ,orderCon: {} });
                        }, 5000)
                    }
                },
                fail: function(res) {
                    setTimeout(function() {
                        that.setData({ showFailPromptDialog: true })
                    }, 3000)
                }
            })
        }

        // 支付
        let bodyCon= '跑腿';
        let commodity_type = 24;
        let data = { bodyCon, commodity_type }

        // 没登录的先登录再付款
        let promise = new Promise(function(resolve, rej) {
            app.login(res => {
                resolve(res)
            })
        })
        let that=this;
        promise.then(
            resolve => {
                wx.request({
                    url: `${API_URL}/payments`,
                    data: data,
                    header: app.header(),
                    method: 'post',
                    success: res=> {
                        wx.requestPayment({
                            nonceStr: res.data.nonceStr,
                            package: res.data.package,
                            paySign: res.data.paySign,
                            signType: "MD5",
                            timeStamp: res.data.timeStamp,
                            success(res) {
                                that.setData({ showUp_loading: true })
                                that.waitForUpload()
                                wx.request({
                                    url: `${API_URL}/delivery`,
                                    data: data_1,
                                    header: app.header(),
                                    method: 'post',
                                    success: function (res) {
                                        if(res.statusCode == 200) {
                                            setTimeout(function () {
                                                that.setData({ showSuccessPromptDialog: true ,orderCon: {} });
                                            }, 5000)
                                        }
                                    },
                                    fail: function(res) {
                                        setTimeout(function() {
                                            that.setData({ showFailPromptDialog: true })
                                        }, 3000)
                                    }
                                })
                            },
                            fail(res) {
                                console.log("取消支付: ", res);
                                wx.showToast({
                                    title: "取消支付",
                                    icon: 'fail',
                                    duration: 2000,
                                    mask: false
                                })
                            }
                        })
                    }
                })
            }
        )
    },

    /**
     * 删除发布内容
     */
    // 获取 Id
    getIndexById(id, arr) {
        this.setData({ destroyId: id })
        for( let i in arr ) {
            if( id == arr[i].id ) {
                return i;
            }
        }
        return -1;
    },

    // 确定删除对
    dialogOnConfirm() {
        let token = null;
        let destroyId = this.data.destroyId;
        wx.getStorage({
            key: 'userInfo',
            success(res) {
                token = res.data.token
                wx.request({
                    url: `${API_URL}/deliveryDestroy`,
                    header: {
                        token: res.data.token
                    },
                    data: { postId: destroyId },
                    method: 'post',
                    success: function (res) {
                        console.log('res: ', res);
                    }
                })
            }
        })

        if (this.data.currentItemIndex) {
            let index = this.data.currentItemIndex
            let arr = this.data.review
            arr.splice(index, 1)
            this.setData({ review: arr })
        }
        this.setData({ showAuthDialog: false })
    },

    // 取消删除
    dialogOnCancel() {
        this.setData({ showAuthDialog: false })
    },

    // 弹出删除对话框
    showDialogtTap(e) {
        let item = e.currentTarget.dataset.item
        this.setData({
            showAuthDialog: true,
            currentItemIndex: this.getIndexById(item.id, this.data.review)
        })
    },

    // 完毕对话框
    dialogOnComplete() {
        this.setData({ showUnfilledDialog: false })
    },
    
    // 成功提示框完毕
    completeDialog() {
        this.setData({ showSuccessPromptDialog: false })
    },

    // 失败提示框完毕
    failCompleteDialog() {
        this.setData({ showFailPromptDialog: false })
    },

    // 编辑内容 
    onEdit(item) {
        let postId = item.currentTarget.dataset.item.id
        let data = { postId }
        getDeliveryDetail(res => {
            if(res.data.type == 1) {
                this.setData({ bangActive: 0 })
            } else if (res.data.type == 2) {
                this.setData({ bangActive: 1 })
            }
            let editId = res.data.id
            let arry = [{},{}]
            if(res.data.type == 1) {
                arry[0].sender = res.data.sender
                arry[0].from = res.data.from
                arry[0].sender_phone = res.data.sender_phone
                arry[0].sender_remark = res.data.sender_remark
                arry[0].idx = 0
                arry[1].idx = 1
                arry[1].receiver = res.data.receiver
                arry[1].shipping_address = res.data.shipping_address
                arry[1].shipping_phone = res.data.shipping_phone
            } else if (res.data.type == 2) {
                arry[0].phoneNum_2 = res.data.phoneNum_2
                arry[0].receiver_2 = res.data.receiver_2
                arry[0].remark_2 = res.data.remark_2
                arry[0].shipping_address_2 = res.data.shipping_address_2
                arry[0].idx = 2
                arry[1].idx = 3
                arry[1].receiver_3 = res.data.receiver_3
                arry[1].sender_phone_3 = res.data.sender_phone_3
                arry[1].shipping_address_3 = res.data.shipping_address_3
            }
            this.setData({ currentIndex: 0, orderCon: arry, editId: editId, userId: wx.getStorageSync('uid') })
        }, data);
    },

    // 全部发送
    allPush() {
        let data = { currentUser:true }
        getDelivery(res => {
            let request = res.data.data
            if (res.statusCode == 200) {
                for (let item of res.data.data) {
                    item.releaseTime = dayjs(item.releaseTime).format("YYYY-MM-DD")
                }
                this.setData({ review: request })
            }
        }, data);
    },

    // 待审核
    pendingReview() {
        let data = { status: 0, currentUser:true }
        getDelivery(res => {
            let request = res.data.data
            if (res.statusCode == 200) {
                for (let item of res.data.data) {
                    item.releaseTime = dayjs(item.releaseTime).format("YYYY-MM-DD")
                }
                this.setData({ review1: request })
            }
        }, data);
    },

    //用户点击bottomTab时调用
    titleClick: function (e) {
        let index = e.currentTarget.dataset.idx
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
        })
        let checkAuth = false;
        switch (index) {
            case '1':
                this.allPush()
                let promise = new Promise(function(resolve, rej) {
                    app.login()
                })
                
                checkAuth = true
                promise.then(
                    resolve => {
                        this.allPush()        
                    }
                )
                break;
            default:
                break;
        }
        let info = wx.getStorageSync('userInfo')
        if (info) {
            this.setData({ userId: wx.getStorageSync('userInfo').user.id })
        }
        if (checkAuth && this.data.userId == 0) return
        this.setData({ currentIndex: e.currentTarget.dataset.idx });
    },

    //用户点击topTab时调用
    topTapClick(e) {
        this.setData({ topTapCurrentIndex: e.currentTarget.dataset.index })
        let index = e.currentTarget.dataset.index
        switch (index) {
            case '0':
                this.allPush()
                break;
            case '1':
                this.pendingReview()
                break;
            default:
                break;
        }
    },

    // 帮送按钮
    onCilckBgs() {
        if (this.data.bangActive == 0) return;
        this.setData({ bangActive: 0, orderCon: [] })
    },

    // 帮送按钮
    onCilckBgq() {
        if (this.data.bangActive == 1) return;
        this.setData({ bangActive: 1, orderCon: [] })
    },

    // 往填写订单页面跳转
    writeCon(e){
        let idx = e.currentTarget.dataset.idx
        let item;
        if(e.currentTarget.dataset.item[0] && e.currentTarget.dataset.item[0].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[0]
        } else if (e.currentTarget.dataset.item[1] && e.currentTarget.dataset.item[1].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[1]
        } else if (e.currentTarget.dataset.item[0] && e.currentTarget.dataset.item[0].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[0]
        } else if (e.currentTarget.dataset.item[1] && e.currentTarget.dataset.item[1].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[1]
        } else if (e.currentTarget.dataset.item[0] && e.currentTarget.dataset.item[0].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[0]
        } else if (e.currentTarget.dataset.item[1] && e.currentTarget.dataset.item[1].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[1]
        } else if (e.currentTarget.dataset.item[0] && e.currentTarget.dataset.item[0].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[0]
        } else if (e.currentTarget.dataset.item[1] && e.currentTarget.dataset.item[1].idx == e.currentTarget.dataset.idx) {
            item = e.currentTarget.dataset.item[1]
        }
        let json = JSON.stringify(item);
        wx.navigateTo({
            url: '/pages/home/runErrands/runErrandsDetailed/runErrandsDetailed?idx=' + idx + "&json=" + json
        });
    },

    // App 默认方法

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({ lang: app.globalData.lang, navTitle: "delivery", navigation: true, userId: wx.getStorageSync('uid') })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        const that = this;
        wx.getLocation({
            type: 'wgs84',
            success (res) {
                that.setData({ locationInfo: res })
            }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1];
        if (currPage.data.infoObj && currPage.data.infoObj.length > 11) {
            let value = JSON.parse(currPage.data.infoObj)
            for(var i=0; i<this.data.orderCon.length; i++){
                if(this.data.orderCon[i].idx == value.idx){
                    this.data.orderCon.splice(i,1);
                }
            }
            this.setData({
                //将携带的参数赋值
                orderCon: this.data.orderCon.concat(value),
            });
            console.log("orderCon: ", this.data.orderCon);
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})